package com.midou.administration.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.midou.administration.bo.*;
import com.midou.administration.bo.CommonResult;
import com.midou.administration.entity.*;
import com.midou.administration.entity.Member;
import com.midou.administration.mapper.*;
import com.midou.administration.mapper.MemberMapper;
import com.midou.administration.service.RedisService;
import com.midou.administration.service.UsersService;
import com.midou.administration.utils.QRCodeUtils;
import com.midou.administration.utils.Token;
import com.midou.administration.utils.Information;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MrChen
 * @since 2021-03-24
 */
@Service
public class UsersServiceImpl implements UsersService {

    private String staticPath = System.getProperty("user.dir")+"\\midou-restaurant-administration\\src\\main\\resources\\static\\image";

    @Autowired
    private UsersMapper mapper;     //直接映射mapper


    @Autowired
    private RedisService redisService;

    @Autowired
    private BusinessMapper businessMapper;


    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private Information information;
    @Autowired
    private OrderMapper orderMapper;
    //餐桌接口
    @Autowired
    private DeskMapper deskMapper;

    /**
     * 会员登录
     * @param name  会员账号
     * @param pwd   会员密码
     * @return  返回消息类 {"result":"结果 boolean类型","msg":"提示消息","token":"成功的token" }
     */
    @Override
    public Msg login(String name, String pwd) {
        Users users = this.mapper.login(name);
        if(users!=null){
            System.out.println(users.getUserPassword()+"查询出的密码");
            System.out.println(pwd+"传递的密码");
            if(users.getUserPassword().equals(pwd)){ users.setUserPicture(QRCodeUtils.ImageToBase64ByLocal(staticPath+"\\"+users.getUserPicture()));
               /*返回token*/
               Msg m =  new Msg(true,"欢迎您:"+users.getUserName());
               m.setToken(getToken(users));                 //获取token后赋值  调用方法
               m.setUserId(users.getUserId());
               m.setUserName(users.getUserName());
               m.setUsers(users);
               return m;
            }else {
                return new Msg(false, "密码不正确,请确认后重试!");
            }
        }

        return new Msg(false,"没有该账户!");
    }

    /**
     * 注册一个会员信息
     * @param users 会员对象
     * @return  在数据库中新增会员的id
     */
    @Override
    public int insert(Users users){
        this.mapper.insert(users);
        return users.getUserId();
    }


    //签发普通用户的token
    public String getToken(Users users){
        Algorithm algorithm = Algorithm.HMAC512(Token.token);
        Date expiresDate = new Date(System.currentTimeMillis() + (1000*60*60*24*3));
        String token = null;
        token = JWT.create()
                .withIssuer("auto0")                 //签发者
                .withClaim("id",users.getUserId())       //向有效载荷中添加用户信息;
                .withExpiresAt(expiresDate)
                .sign(algorithm);                    //计算签名
        return token;
    }

    //查询所有会员基础信息
    public Page userMember(UserBo userBo){
        System.out.println(userBo.getPhone());
        if(userBo.getPhone()==null){
            userBo.setPhone("");
        }
        if(userBo.getPhone().equals("")){
            userBo.setPhone(null);
        }
        List<Users> usersList=mapper.userMember(userBo.getPage(),userBo.getUserBusinessId(),userBo.getPhone());
        userBo.getPage().setRecords(usersList);
        return userBo.getPage();
    }

    //发送短信验证码的业务
    @Override
    public Msg send(String phone) {
        //考虑 是否要在没有账户时注册  有账户时登录
        //判断该账号是否存在
//        QueryWrapper query = new QueryWrapper();
//        query.eq("",phone);
//        Integer count = this.mapper.selectCount(query);
        //生成验证码
        String code = information.generateCode();
        System.out.println("短信验证码是"+code);
        Boolean result = information.send(phone,code);
//        保存验证码3分钟
        this.information.store(phone,code);
        if(result){
            return new Msg(true,"发送成功!");  //发送成功 1
        }
        return new Msg(false,"发送失败!");      //发送失败 1
    }

    /**
     * 验证验证码是否正确
     * @param phone 手机号
     * @param code  用户输入的验证码
     * @return  代码  0正确 1表示验证码不正确   2表示验证码过期或不存在
     */
    @Override
    public int verify(String phone, String code) {
        return information.verify(phone, code);
    }

    //修改前根据ID查询要修改的会员信息
    public Users updateUserSelect(Integer userId){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        return mapper.selectOne(queryWrapper);
    }

    //修改会员信息
    public Integer updateNemBer(Users users){
        return mapper.updateById(users);
    }
    //添加会员信息
    public Integer saveVip(Users users){
        return mapper.insert(users);
    }
    //查询会员账号是否重复
    public List<Users> userCode(String userCode,Integer userBusinessId){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_code",userCode);
        queryWrapper.eq("user_business_id",userBusinessId);
       List<Users> us =mapper.selectList(queryWrapper);
        return us;
    }
    //验证手机号是否重复
    public List<Users> userPhone(String phone,Integer userBusinessId){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_phone",phone);
        queryWrapper.eq("user_business_id",userBusinessId);
        List<Users> us =mapper.selectList(queryWrapper);
        return us;
    }
    //会员充值
    public CommonResult vipChongQian(UserBo users){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_phone",users.getPhone());
        queryWrapper.eq("role_id",5);
       Users users1=mapper.selectOne(queryWrapper);
        users1.setUserCumulative(users1.getUserMoney()+users.getJe());
        users1.setUserMoney(users1.getUserMoney()+users.getJe());
       if(users1==null) {
           return new CommonResult(500, "该手机号还未注册成为会员");
       }
       if(users1.getUserCumulative()>=2000&&users.getJe()<3000){
           users1.setUserLevel("2");
           users1.setUserDiscount(20.f);
       }
       if(users1.getUserCumulative()>=3000){
           users1.setUserLevel("3");
           users1.setUserDiscount(30.f);
       }



       users1.setUserIntegral(new Double(users.getJe()).intValue()+ users1.getUserIntegral());
       Integer num=mapper.updateById(users1);
        int random= (int) (Math.random()*10+1);
        Member member=new Member();
        member.setMemCardNumber(String.valueOf(random));
        member.setMemRechargeTime(new Date());
        member.setMemRecharge(users.getJe());
        member.setClerkId(users.getClearkId());
        member.setUserId(users1.getUserId());
        member.setMemBalance(users1.getUserMoney());
        num+=memberMapper.insert(member);
       if(num==2){
           return new CommonResult(200,"充值成功");
       }
       return null;
    }
    //删除会员
    public CommonResult deleteMenBer(Integer id){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",id);
        Users users=mapper.selectOne(queryWrapper);
        users.setRoleId(4);
        if(users.getUserMoney()>0){
            return new CommonResult(500,"该会员还有余额未使用,无法删除");
        }
        Integer num=mapper.updateById(users);
        if(num>0){
            return new CommonResult(200,"删除成功");
        }
        return null;
    }

    /*去重操作*/
    @Override
    public Msg repetition(Users users) {
        int num = this.mapper.repetition(users.getUserCode());
        if(num>0){
            return new Msg(false,"该账号已经被注册,请直接进行登录!");
        }else{
            return new Msg(true,"允许使用");
        }
    }

    //修改密码
    @Override
    public Msg updPwdById(uniApp uniApp) {
        Users user = this.mapper.selectById(uniApp.getUserId());

        /**
         * 判断绑定的手机号与输入的手机号是否相同
         */
        if(user.getUserPhone().equals(uniApp.getPhone()) == false){
            return new Msg(false,"鉴于您当前的操作环境，我们不建议您进行修改密码操作!");
        }
        /**
         * 验证验证码是否正确
         */
        String code = this.redisService.getAuthCode(uniApp.getPhone());
        System.out.println("该手机获取的验证码是:" + code);
        if(code==null){
            return new Msg(false,"请点击发送验证码");
        }

        if(code.equals(uniApp.getCode()) == false){
            //验证码错误的
            return new Msg(false,"验证码输入错误!");
        }


        if(user==null){
            return new Msg(false,"请登录后重试!");
        }

//        if(!user.getUserPassword().equals(users.getUserPassword())){
//            return new Msg(false,"原密码不正确,请稍后重试!");
//        }

        if(user.getUserPassword().equals(uniApp.getNewPwd())){
            return new Msg(false,"新密码不能与历史密码相同!");
        }



        user.setUserPassword(uniApp.getNewPwd());
        this.mapper.updateById(user);

        return new Msg(true,"修改成功,请牢记修改后密码。");
    }
    //<!--    查询会员优惠额度-->
    public Users cxjg(String phone){
        return mapper.jsjg(phone);
    }
    //vip消费
    public CommonResult vipZhiFu( UserBo userBo){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_phone",userBo.getUserPhone());
        Users users=mapper.selectOne(queryWrapper);
        if(!userBo.getUserPaymentCode().equals(users.getUserPaymentCode())){
            return new CommonResult(500,"支付密码不正确");
        }else {
            if(users.getUserMoney()>=userBo.getMoney()){
                users.setUserIntegral(0);
                users.setUserMoney(users.getUserMoney()-userBo.getMoney());
                Integer num=mapper.updateById(users);
                Member member=new Member();
                member.setUserId(users.getUserId());
                member.setMemBalance(users.getUserMoney());
                member.setMemConsumption(userBo.getMoney());
                member.setMemConsumptionTime(new Date());
                member.setClerkId(userBo.getClerkId());
                member.setMemCardNumber(userBo.getOrderNumber());
                QueryWrapper queryWrapper1=new QueryWrapper();
                queryWrapper1.eq("order_number",userBo.getOrderNumber());
                Order order=orderMapper.selectOne(queryWrapper1);
                order.setOrderState(1);
                order.setOrderPaymentMethod(1);
                order.setOrderPrice(userBo.getMoney());
                Desk desk = this.deskMapper.selectById(order.getDeskId());
                desk.setDeskStatus(3);
                this.deskMapper.updateById(desk);
                QueryWrapper queryWrapper2=new QueryWrapper();
                queryWrapper2.eq("bu_id",userBo.getUserBusinessId());
                Business busines=businessMapper.selectOne(queryWrapper2);
                busines.setBuProfit(busines.getBuProfit()+userBo.getMoney());
                businessMapper.updateById(busines);
                num+=orderMapper.updateById(order);
                num+=memberMapper.insert(member);
                if(num>=3){
                    return new CommonResult(200,"支付成功");
                }
            }else {
                return new CommonResult(500,"该会员余额不足,无法支付");
            }

        }
        return null;
    }



}
